package com.zmn.oms.api.controller.third.gomegj;

import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.common.utils.RequestUtil;
import com.zmn.oms.third.gomegj.GmgjConsts;
import com.zmn.oms.third.gomegj.dto.GmgjRequestDTO;
import com.zmn.oms.third.gomegj.dto.GmgjResponseDTO;
import com.zmn.oms.third.gomegj.service.GmgjService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 类描述：国美管家对外接口
 * 用于国美管家向我方的订单推送及订单状态变更推送
 *
 * @author XieWenBing
 * @date 2020/11/04 11:00
 */
@RestController
@RequestMapping("/gomegj")
@Slf4j
public class GomeGuanjiaController {

    @Autowired
    protected GmgjService gmgjService;

    @PostMapping("/api/syncOrder")
    @ResponseBody
    public GmgjResponseDTO syncOrder(HttpServletRequest httpServletRequest) {

        GmgjResponseDTO responseDTO = new GmgjResponseDTO();
        if (!GmgjConsts.POWER_ON) {

            responseDTO.setCode(GmgjConsts.RESPONSE_CODE_SYSTEM_ERROR);
            responseDTO.setMsg("服务接口暂不支持");
            return responseDTO;
        }

        GmgjRequestDTO gmgjRequestDTO = new GmgjRequestDTO();
        gmgjRequestDTO.setMsgId(httpServletRequest.getParameter("msgId"));
        gmgjRequestDTO.setMethod(httpServletRequest.getParameter("method"));
        gmgjRequestDTO.setSign(httpServletRequest.getParameter("sign"));
        gmgjRequestDTO.setBody(RequestUtil.getPostParameter(httpServletRequest));

        log.info("【{}】收到订单消息！ Body:[{}]", GmgjConsts.CHANNEL_NAME, gmgjRequestDTO.toString());

        try {
            gmgjService.handleOrderMsg(gmgjRequestDTO);
            responseDTO.setCode(GmgjConsts.RESPONSE_CODE_SUCCESS);
            responseDTO.setMsg("SUCCESS");
        } catch (OmsBaseException omsBaseException) {

            log.info("【{}】处理消息异常 【{}】【{}】",GmgjConsts.CHANNEL_NAME, omsBaseException.getCode(), omsBaseException.getMessage());
            // 发生异常或错误
            responseDTO.setCode(omsBaseException.getCode());
            responseDTO.setMsg(GmgjConsts.getErrorMsg(omsBaseException.getCode()));
        }

        log.info("【{}】处理消息结果 [{}]", GmgjConsts.CHANNEL_NAME, responseDTO.toString());
        return responseDTO;
    }
}
